/**
 * long description for the file
 *
 * @summary short description for the file
 * @author wu[308822989@qq.com]
 *
 * Created at     : 2019-06-12 22:59:54 
 * Last modified  : 2019-08-11 13:05:33
 */

const axios = require('axios');
const utils = require('utility');
const querystring = require('querystring');

//  aid
const AID = '';
//  secret 密钥
const SECRET = '';
//  请求服务器地址
const BASE_URL = 'https://api.yiyunpay.cn'

const TIME_OUT = 60 * 1000;


/**
 * 易云支付类
 */
class Yiyunpay {
    //
    constructor(aid = AID, secret = SECRET, baseURL = BASE_URL, timeout = TIME_OUT) {
        this.aid = aid;
        this.secret = secret;
        //  HTTP
        this.instance = axios.create({
            baseURL: baseURL,
            //  请求超时时间
            timeout: timeout,
        });
        // 添加请求拦截器
        this.instance.interceptors.request.use((config) => {
                // 在发送请求之前做些什么
                //  POST 数据签名
                !config.data && (config.data = {});
                !config.data.sign && (config.data.sign = getSign(objectSort((config.data || {})), this.secret));
                //
                return config;
            }, function (error) {
                // 对请求错误做些什么
                return Promise.reject(error);
            });
    }

    /**
     * 添加订单
     * @param {Object} orderItem 订单信息
     * @returns {Promise} Object
     */
    async orderAdd (orderItem) {
        let item = {
            ...orderItem,
            aid: this.aid,
        }
        return this.instance.post('/admin/order/add', item).then(res => {
            if (res.status === 200) {
                return res.data;
            } else {
                return {};
            }
        });
    }

    /**
     * 用户信息
     * @returns {Promise} Object
     */
    async memberInfo () {
        let item = {
            aid: this.aid,
        }
        return this.instance.post('/admin/order/memberinfo', item).then(res => {
            if (res.status === 200) {
                return res.data;
            } else {
                return {};
            }
        });
    }

    /**
     * 订单详情
     * @param {String} order_id 订单信息
     * @returns {Promise} Object
     */
    async orderInfo (order_id) {
        let item = {
            order_id,
            aid: this.aid,
        }
        return this.instance.post('/admin/order/orderinfo', item).then(res => {
            if (res.status === 200) {
                return res.data;
            } else {
                return {};
            }
        });
    }
    /**
     * 支付类型列表
     * @returns {Promise} Array
     */
    async typeItems () {
        let item = {
            aid: this.aid,
        }
        return this.instance.post('/admin/order/typelist', item).then(res => {
            if (res.status === 200 && res.data.errno === 0) {
                return res.data.data;
            } else {
                return [];
            }
        });
    }

    /**
     * 系统信息查询
     * @returns {Promise} Array
     */
    async sysConfig () {
        let item = {
            aid: this.aid,
        }
        return this.instance.post('/admin/order/typelist', item).then(res => {
            if (res.status === 200 && res.data.errno === 0) {
                return res.data.data;
            } else {
                return {};
            }
        });
    }


    /**
     * 收款商品列表
     * @returns {Promise} Array
     */
    async qcodeItems () {
        let item = {
            aid: this.aid,
        }
        return this.instance.post('/admin/order/qcodelist', item).then (res => {
            if (res.status === 200 && res.data.errno === 0) {
                return res.data.data;
            } else {
                return [];
            }
        });
    }


    /**
     * 登录
     * @returns {Promise} Object
     */
    async login (data) {
        let item = data;
        return this.instance.post('/admin/login/index', item).then (res => {
            if (res.status === 200) {
                return res.data;
            } else {
                return {};
            }
        });
    }



    /**
     * 注册
     * @returns {Promise} Object
     */
    async loginin (data) {
        let item = data;
        return this.instance.post('/admin/login/loginin', item).then (res => {
            if (res.status === 200) {
                return res.data;
            } else {
                return {};
            }
        });
    }

    /**
     * 收款商品列表
     * @returns {Promise} Array
     */
    async getPayObj () {
        return Promise.all([this.sysConfig(), this.qcodeItems(), this.typeItems()]).then(resArr => {
            return res = {
                status: true,
                msg: '',
                sysConfig: resArr[0],
                qcodeItems: resArr[1],
                typeItems: resArr[1],
            }
        }).catch(err => {
            return res = {
                status: false,
                msg: err.message,
                sysConfig: {},
                qcodeItems: [],
                typeItems: [],
            }
        });      
    }
}




//  对象 ascii码排序
const objectSort = function (obj) {
    let arr = new Array();
    let num = 0;
    for (let i in obj) {
      arr[num] = i;
      num++;
    }
    let sortArr = arr.sort();
    let sortObj = {};
    for (let i in sortArr) {
      sortObj[sortArr[i]] = obj[sortArr[i]];
    }
    return sortObj;
}

//  对象 URL加密码
const getSign = function (obj, secret) {
    let urlStr = querystring.stringify(obj);
    return utils.md5(`${urlStr}&secret=${secret}`);
}



module.exports = {
    Yiyunpay,
    objectSort,
    getSign,
};